package sniff.diller;

import jpcap.packet.Packet;
import sniff.pack.MyHTTPPacket;
import sniff.pack.MyHTTPRequestPack;
import sniff.pack.MyHTTPResponsePacket;

public class HTTPPacketDiller {
	public static MyHTTPPacket dill(Packet pack) {
		byte[] data = pack.data;
		String dataString = new String(data);
		String[] datas = dataString.split("\r\n");
		String[] beginLine = datas[0].split(" ");
		MyHTTPPacket httpPack=null;
		StringBuffer headLine=new StringBuffer();
		for(int i=1;i<datas.length;i++) {
			headLine.append(data[i]+"\r\n");
		}
		if(beginLine[0].contains("HTTP")) {//响应报文
			String httpVersion = beginLine[0];
			String statusCode = beginLine[1];
			String responsePhrase="";
			if(beginLine.length==3) {
				responsePhrase = beginLine[2];
			}
			httpPack = new MyHTTPResponsePacket(headLine.toString(), httpVersion, statusCode, responsePhrase);
			httpPack.setInfo(datas[0]);
		}else if(beginLine[2].contains("HTTP")) {//请求报文
			String method = beginLine[0];
			String url = beginLine[1];
			String httpVersion = beginLine[2];
			httpPack = new MyHTTPRequestPack(headLine.toString(), httpVersion, method, url);
			httpPack.setInfo(datas[0]);
		}else {//未知
			return null;
		}
		return httpPack;
	}
	
	public static boolean isHttpPacket(Packet pack) {
		byte[] data = pack.data;
		String dataString = new String(data);
		String[] datas = dataString.split("\r\n");
		if(datas[0].contains("HTTP")) {
			return true;
		}else {
			return false;
		}
	}
}
